package com.daocheng.dc.book.kv.biz.service.impl;

import com.daocheng.dc.book.kv.biz.domain.dataobject.NoteContentDO;
import com.daocheng.dc.book.kv.biz.domain.repository.NoteContentRepository;
import com.daocheng.dc.book.kv.biz.enums.ResponseCodeEnum;
import com.daocheng.dc.book.kv.dto.req.AddNoteContentReqDTO;
import com.daocheng.dc.book.kv.biz.service.NoteContentService;
import com.daocheng.dc.book.kv.dto.req.DeleteNoteContentReqDTO;
import com.daocheng.dc.book.kv.dto.req.FindNoteContentReqDTO;
import com.daocheng.dc.book.kv.dto.rsp.FindNoteContentRspDTO;
import com.daocheng.framework.common.exception.BizException;
import com.daocheng.framework.common.response.Response;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * @ClassName NoteContentServiceImpl
 * @author: 稻城
 * @date: 2025/4/3
 * @Version 1.0
 * @description: TODO
 */
@Service
public class NoteContentServiceImpl implements NoteContentService {
    @Resource
    private NoteContentRepository noteContentRepository;

    @Override
    public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
        Long noteId = addNoteContentReqDTO.getNoteId();
        String noteContent = addNoteContentReqDTO.getContent();
        NoteContentDO noteContentDO = NoteContentDO.builder()
                .id(UUID.randomUUID())
                .content(noteContent)
                .build();
        noteContentRepository.save(noteContentDO);
        return Response.success();
    }

    @Override
    public Response<FindNoteContentRspDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
        String noteId = findNoteContentReqDTO.getNoteId();
//        NoteContentDO noteContentDO = noteContentRepository.findById(UUID.fromString(noteId)).orElse(null);
        // 根据笔记 ID 查询笔记内容
        Optional<NoteContentDO> optional = noteContentRepository.findById(UUID.fromString(noteId));
        // 若笔记内容不存在
        if (!optional.isPresent()) {
            throw new BizException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }

        NoteContentDO noteContentDO = optional.get();
        // 构建返参 DTO
        FindNoteContentRspDTO findNoteContentRspDTO = FindNoteContentRspDTO.builder()
                .noteId(noteContentDO.getId())
                .content(noteContentDO.getContent())
                .build();

        return Response.success(findNoteContentRspDTO);
    }

    @Override
    public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
        String noteId = deleteNoteContentReqDTO.getNoteId();
        noteContentRepository.deleteById(UUID.fromString(noteId));
        return Response.success();
    }
}
